package com.nio;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @description
 * @author: wangtao
 * @date:16:09 2018/12/20
 * @email:taow02@jumei.com
 */
public class Test {

	public static void main(String[] args) {
		Channel channel = new NioServerSocketChannel();
		ChannelFuture channelFuture = channel.connect(new InetSocketAddress("127.0.0.1", 333));

		channelFuture.addListener((ChannelFutureListener) cf -> {
			cf.channel();
			System.out.println(cf.isSuccess());
			ByteBuf buffer = Unpooled.copiedBuffer("Hello", Charset.defaultCharset()); //4
			ChannelFuture wf = cf.channel().writeAndFlush(buffer);
		});
	}

	@ChannelHandler.Sharable //1
	public class EchoServerHandler extends ChannelInboundHandlerAdapter {
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) {
			ByteBuf in = (ByteBuf) msg;
			System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));//2
			ctx.write(in); //3
		}

		@Override
		public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
			ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4
					.addListener(ChannelFutureListener.CLOSE);
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
			cause.printStackTrace(); //5
			ctx.close(); //6
		}
	}

}
